package com.glodon.paas.job.server.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glodon.paas.job.model.Task;
import com.glodon.paas.job.server.service.TaskService;
import com.glodon.paas.job.util.JsonUtil;

@Controller
@SuppressWarnings({ "rawtypes" })
public class TaskController {
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);

    @Autowired
    private TaskService taskService;

    @RequestMapping(value = "/task/{type}", method = RequestMethod.POST)
    public void add(@PathVariable String type, @RequestBody String json, HttpServletResponse resp) throws Exception {
        logger.debug("add task - type: {}, json: {}", type, json);
        Map params = JsonUtil.jsonToMap(json);
        Task task = taskService.addTask(type, params);
        resp.getWriter().print(task.toJson());
    }

    @RequestMapping(value = "/task", method = RequestMethod.GET)
    public void getAll(HttpServletResponse resp) throws Exception {
        List<Task> tasks = taskService.getAllTask();
        resp.getWriter().print(JsonUtil.objectToJson(tasks));
    }

    @RequestMapping(value = "/task/{id}", method = RequestMethod.GET)
    public void get(@PathVariable String id, HttpServletResponse resp) throws Exception {
        logger.debug("get task - id: {}", id);
        Task task = taskService.getTask(id);
        if (task == null) {
            resp.sendError(404, "task not found, id is " + id);
        } else {
            resp.getWriter().print(task.toJson());
        }
    }

    @RequestMapping(value = "/task/{id}", method = RequestMethod.DELETE)
    public void cancel(@PathVariable String id, HttpServletResponse resp) throws Exception {
        logger.debug("cancel task - id: {}", id);
        Task task = taskService.getTask(id);
        if (task == null) {
            resp.sendError(404, "task not found, id is " + id);
        } else {
            taskService.cancelTask(task);
            resp.getWriter().print(task.toJson());
        }
    }
}
